const {
  createUser,
  getUserInfo,
  updateById,
  getUserListAllServer,
  deleteUser,
  updateUser,
} = require("../server/user.server");
const {
  userRegisterError,
  failUpdatePasswordServer,
  failUpdatePassword,
  successUpdatePasswordServer,
  userAllListFromatterError,
  userDeleteError,
  userUpdateError,
} = require("../constants/err.type");

const jwt = require("jsonwebtoken");

const { JWT_SECRET } = require("../config/config.default");

class UserController {
  // 注册
  async register(ctx, next) {
    // 获取前端传来的值
    const { user_name, password, roleId } = ctx.request.body;

    try {
      // 操作数据库
      const result = await createUser(user_name, password);
      // 返回结果
      (ctx.state.user = {
        id: result.id,
        user_name: result.user_name,
        roleId: roleId || null,
      }),
        await next();
    } catch (error) {
      console.error(error)((ctx.body = userRegisterError));
    }
  }

  // 登录
  async login(ctx, next) {
    const { user_name } = ctx.request.body;

    // 获取用户信息（token中payload中，记录id，user_name,is_admin）
    try {
      const { password, ...res } = await getUserInfo({
        user_name,
      });

      ctx.body = {
        code: 0,
        message: "用户登录成功",
        result: {
          access_token: jwt.sign(res, JWT_SECRET, {
            expiresIn: "1d",
          }),
        },
      };
    } catch (error) {
      console.error("用户登录失败", error);
    }
  }

  // 修改密码
  async resetPassword(ctx, next) {
    const { id } = ctx.state.user;
    const { password } = ctx.request.body;
    // 操作数据库
    try {
      if (
        await updateById({
          id,
          password,
        })
      ) {
        ctx.body = successUpdatePasswordServer;
      } else {
        ctx.body = failUpdatePassword;
      }
    } catch (error) {
      console.error("服务器错误 修改密码失败 ", error);
      ctx.body = failUpdatePasswordServer;
    }
    // 返回结果
  }

  // 获取用户信息
  async getUserInfo(ctx, next) {
    const {
      user: { iat, exp, ...result },
    } = ctx.state;
    ctx.body = {
      code: 0,
      message: "获取用户信息成功",
      result: result,
    };
  }

  // 获取用户列表
  async getUserListAll(ctx, next) {
    try {
      const result = await getUserListAllServer();
      if (result) {
        ctx.body = {
          code: 0,
          message: "获取用户列表成功",
          result: result,
        };
      } else {
        ctx.body = userAllListFromatterError;
      }
    } catch (error) {
      console.error(error);
      ctx.body = userAllListFromatterError;
    }
  }

  // 修改用户信息
  async updateUser(ctx, next) {
    try {
      const result = await updateUser(ctx.request.body);
      if (result) {
        ctx.body = {
          code: 0,
          message: "修改用户信息成功",
          result: "",
        };
      } else {
        ctx.body = userUpdateError;
      }
    } catch (error) {
      console.error(error);
      ctx.body = userUpdateError;
    }
  }

  // 删除用户信息
  async deleteUsers(ctx, next) {
    const { id } = ctx.request.body;
    try {
      const result = await deleteUser({ id });
      // if (result.result && result.roleResult) {
      if (result.result) {
        ctx.body = {
          code: 0,
          message: "删除用户信息成功",
          result: "",
        };
      } else {
        ctx.body = userDeleteError;
      }
    } catch (error) {
      console.error(error);
      ctx.body = userDeleteError;
    }
  }
}

module.exports = new UserController();
